import React, { Component } from 'react'
import { Toast } from 'antd-mobile'
import { NavBar, Image, FlatList, Radio, Button } from 'components'
import { post, msg, NotColl } from '../../../utils'
import { hash } from 'muka'
import moment from 'moment'
import { Link } from 'react-router-dom'

interface IState {
    isLoading: boolean,
    hasMore: boolean,
    editClass: string,
    selectAll: boolean
    editStatus: boolean
}

export default class MyCollection extends Component<any, IState> {

    public state = {
        isLoading: true,
        hasMore: true,
        editClass: 'footPrint_listViewItem_editBtn_default',
        selectAll: false,
        editStatus: false
    }

    private index: number = 1

    public render(): JSX.Element {
        const { editStatus, selectAll } = this.state
        const { footprintData } = this.props
        return (
            <section className={`footPrint ${(footprintData.length > 0) ? 'footPrint_bgWhite' : ''}`}>
                <div className="footPrint_placehoder">
                    <div className="footPrint_top">
                        <NavBar
                            title={<div className="footPrint_topWrap">
                                <div>我的足迹</div>
                                {!editStatus ? (footprintData.length > 0) ? <span onClick={this.handleEmpty}>清空</span> : '' : null}
                            </div>
                            }
                            right={
                                <div className="footPrint_NavRight">
                                    {
                                        (footprintData.length > 0)
                                            ? <div>
                                                {!editStatus ? <span onClick={this.handleEdit.bind(this, true)}>编辑</span> : <span onClick={this.handleEdit.bind(this, false)}>完成</span>}
                                            </div>
                                            : ''
                                    }

                                </div>}
                        />
                    </div>
                </div>
                <FlatList
                    className="footPrint_listView"
                    data={footprintData}
                    onRefresh={this.getData}
                    ListEmptyComponent={NotColl}
                    renderItem={(item: any, index: number) => {
                        return (
                            <div key={index}>
                                <div style={{ padding: '0 0.7rem' }}>
                                    <div className="footPrint_listView_timebar">{item.time}</div>
                                    <div>
                                        {
                                            item.value.map((itemData: any, i: number) => {
                                                return (
                                                    <Link to={`/shopDetail/${itemData.id}`} key={index + i}>
                                                        <div className="footPrint_listViewItem">
                                                            {editStatus && <div className="flex_justify">
                                                                <Radio checked={itemData.active} onChange={this.handleChange.bind(this, index, i)} />
                                                            </div>}
                                                            <Image src={itemData.pic} className="footPrint_listViewItem_goodsImg" />
                                                            <div className="footPrint_listViewItem_goodsInfo">
                                                                <div className="footPrint_listViewItem_goodsInfo_title">
                                                                    {itemData.name}
                                                                </div>
                                                                <div className="footPrint_listViewItem_goodsInfo_priceInfo">
                                                                    <p>
                                                                        <span>￥</span>
                                                                        <span className="DINPro">{itemData.price}+{itemData.price_q}</span>
                                                                        <span>恒豆</span>
                                                                    </p>
                                                                    {/* {editStatus ? '' : <p className="footPrint_listViewItem_goodsInfo_findBtn">找相似</p>} */}
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </Link>
                                                )
                                            })
                                        }
                                    </div>
                                </div>
                                <div style={{ backgroundColor: '#f4f5f7', height: '0.5rem', width: '100%' }} />
                            </div>

                        )
                    }
                    }
                />
                {
                    editStatus
                        ? <div>
                            <div className="footPrint_editOperationBar_placeholder" />
                            <div className="footPrint_editOperationBar">
                                <div className="flex_justify">
                                    <Radio checked={selectAll} onChange={this.handleSelectAll}>
                                        <span className="footPrint_editOperationBar_selectAll">全选</span>
                                    </Radio>
                                </div>
                                <div>
                                    <Button className="footPrint_editOperationBar_del" onClick={this.handleDelete}>删除</Button>
                                </div>
                            </div>
                        </div>
                        : ''
                }
            </section>
        )
    }
    private getData = (finishLoad: () => void) => {
        const { userInfo, SET_USER_FOOTPRINT } = this.props
        post('usersapi/userFootprints', {
            userId: userInfo.id,
            page: this.index
        }).then((data: any) => {
            const val = this.initData(data.data)
            if (this.index === 1) {
                this.index++
                SET_USER_FOOTPRINT(val)
                finishLoad()
            } else {
                const { footprintData } = this.props
                const arr: any = [...footprintData]
                SET_USER_FOOTPRINT(arr.concat(val))
                if (data.data.length) {
                    this.index++
                    finishLoad()
                }
            }
        })
    }

    private handleChange = (index: number, i: number, val: boolean, e: React.MouseEvent<HTMLDivElement>) => {
        e.preventDefault()
        const { SET_USER_FOOTPRINT, footprintData } = this.props
        const data: any[] = [...footprintData]
        data[index].value[i].active = val
        SET_USER_FOOTPRINT(data)
        this.setState({
            selectAll: data.every((item: any) => {
                return item.value.every((c: any) => c.active)
            })
        })
    }

    private initData(data: any[] = []) {
        const value: any = {}
        const newValue: any[] = []
        data.map((item: any) => {
            if (!hash(value, item.f_time)) {
                value[item.f_time] = []
            }
            value[item.f_time].push({ ...item.get_goods_list, footprint_id: item.id, active: false })
        })
        for (let i in value) {
            newValue.push({
                time: i,
                value: value[i]
            })
        }

        return newValue.sort((a: any, b: any) => {
            const time = moment(a.time)
            const nextTime = moment(b.time)
            if (time > nextTime) {
                return -1
            } else {
                return 1
            }
        })
    }

    private handleEdit = (status: boolean) => {
        if (status) {
            const { SET_USER_FOOTPRINT, footprintData } = this.props
            const data = footprintData.map((item: any) => {
                item.value = item.value.map((i: any) => {
                    i.active = false
                    return i
                })
                return item
            })
            SET_USER_FOOTPRINT(data)
        }
        this.setState({
            editStatus: status,
            selectAll: false
        })
    }

    private handleSelectAll = (status: boolean) => {
        const { SET_USER_FOOTPRINT, footprintData } = this.props
        const data = footprintData.map((item: any) => {
            item.value = item.value.map((i: any) => {
                i.active = status
                return i
            })
            return item
        })
        SET_USER_FOOTPRINT(data)
        this.setState({
            selectAll: status
        })
    }
    private handleEmpty = () => {
        msg('确定要删除全部浏览纪录么？').then(() => {
            const { SET_USER_FOOTPRINT, userInfo } = this.props
            post('goodsapi/delFootprints', {
                ids: 'all',
                userId: userInfo.id
            }).then(() => {
                setTimeout(() => { SET_USER_FOOTPRINT([]); Toast.hide() }, 2000)
            })
        })
    }
    private handleDelete = () => {
        msg('确定要删除浏览纪录么？').then(() => {
            const { SET_USER_FOOTPRINT, footprintData, userInfo } = this.props
            const ids: string[] = []
            const newData: any[] = []
            Toast.loading('', 0)
            footprintData.map((item: any, index: number) => {
                newData.push({ time: item.time, value: [] })
                item.value = item.value.map((i: any) => {
                    if (i.active) {
                        ids.push(i.footprint_id)
                    } else {
                        newData[index].value.push(i)
                    }
                })
            })
            post('goodsapi/delFootprints', {
                ids: ids.join(','),
                userId: userInfo.id
            }).then(() => {
                setTimeout(() => { SET_USER_FOOTPRINT(newData); Toast.hide() }, 2000)
            })
        })
    }
}